package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MovementAsyncService {
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询好友保存好友动态
    @Async
    public void saveMovementFriend(Movement movement) {
//3 查询好友
        //3-1构建条件
        Query query = new Query(
                Criteria.where("userId").is(movement.getUserId())
        );
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if (CollectionUtil.isNotEmpty(friends)) {
            for (Friend friend : friends) {

                Long friendId = friend.getFriendId();

                FriendMovement friendMovement = new FriendMovement();

                friendMovement.setUserId(movement.getUserId());
                friendMovement.setPublishId(movement.getId());
                friendMovement.setCreated(movement.getCreated());
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friendId);
            }
        }
    }
}
